package com.zhanglijie.improve.collections.delayqueue.demo.timecache;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/12/4 0004 20:04
 */
public class DelayObject<T> implements Delayed {
    //这个最其实时间最好还是1884年10月13日国际初始时间，防止容器重启就会改变
    private static final long NANOS_ORIGIN = System.nanoTime();
    private final long time;
    private final T item;
    private static final AtomicLong sequence = new AtomicLong(0);
    private final long sequenceNum;


    public DelayObject(T item,long timeOut){
        this.item = item;
        time = now()+timeOut;
        //当时间相等时用这个序列作为出队优先级条件
        this.sequenceNum = sequence.getAndIncrement();
    }
    public T getItem(){
        return this.item;
    }
    final static long now(){
        return System.nanoTime()-NANOS_ORIGIN;
    }
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(time-now(),TimeUnit.NANOSECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        if(o == this){
            return 0;
        }
        if(o instanceof DelayObject ){
            DelayObject delayObject = (DelayObject) o;
            long diffTime = time-delayObject.time;
            if(diffTime <0){
                return -1;
            }
            else if(diffTime > 0 ){
                return 1;
            }
            else if(sequenceNum < delayObject.sequenceNum){
                return -1;
            }
            return 1;
        }
        long delay = o.getDelay(TimeUnit.NANOSECONDS)-getDelay(TimeUnit.NANOSECONDS);
        return delay == 0?0:(delay<0)?-1:1;
    }



}
